package com.brainhealth.customer.service.impl;

import com.alibaba.fastjson2.JSON;
import com.brainhealth.common.constant.CacheConstants;
import com.brainhealth.common.core.redis.RedisCache;
import com.brainhealth.customer.domain.Customer;
import com.brainhealth.customer.handle.NettyConfig;
import com.brainhealth.customer.service.IWebsocketService;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebsocketServiceImpl implements IWebsocketService
{
    private static final Logger logger = LoggerFactory.getLogger(WebsocketServiceImpl.class);

    @Autowired
    RedisCache redisCache;

    @Override
    public void pushMsgToOne(String userId, String msg)
    {
        ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
        Channel channel = userChannelMap.get(userId);
        channel.writeAndFlush(new TextWebSocketFrame(msg));
    }

    @Override
    public void pushMsgToAll(String msg)
    {
        ChannelGroup channelGroup = NettyConfig.getChannelGroup();
        channelGroup.writeAndFlush(new TextWebSocketFrame(msg));
    }

    @Override
    public List<Customer> getOnlineCustomerList()
    {
        ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
        logger.info("当前在线用户" + JSON.toJSONString(userChannelMap));
        List<Customer> lstOnlineCustomer = new ArrayList<>();
        Collection<String> keys = redisCache.keys(CacheConstants.CUSTOMER_TOKEN + "*");
        for (String key : keys)
        {
            String jsonString = redisCache.getCacheObject(key);
            Customer customer = JSON.parseObject(jsonString, Customer.class);
            if (userChannelMap.keySet().contains(customer.getPhone()))
            {
                lstOnlineCustomer.add(customer);
            }
        }
        return lstOnlineCustomer;
    }

}
